from flask import current_app, jsonify, g, render_template, request,session,redirect

from info import constants
from info import db
from info.models import Category, News
from info.utils.image_storage import storage
from . import profile_blu
from info.utils.common import user_login_data
from info.utils.response_code import RET

# 个人中心
@profile_blu.route('/info')
@user_login_data
def user_info():
    # 判断用户是否登陆
    user = g.user
    if not user:
        return redirect('/')
    data = {
        'user':user.to_dict()
    }
    return render_template('news/user.html',data=data)


@profile_blu.route('/base_info',methods=['GET','POST'])
@user_login_data
def base_info():

    user = g.user
    if request.method == 'GET':
        if not user:
            return redirect('/')
        data = {
            'user': user.to_dict()
        }
        return render_template('news/user_base_info.html', data=data)

    # 获取表单参数,
    data_dict = request.json
    nick_name = data_dict.get('nick_name')
    gender = data_dict.get('gender')
    signature = data_dict.get('signature')

    if not all([nick_name,gender,signature]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')

    if gender not in ('MAN','WOMAN'):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')

    # 保存数据
    user.nick_name = nick_name
    user.gender = gender
    user.signature = signature

    # 提交数据
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.roolback()
        return jsonify(errno=RET.DBERR,errmsg='保存数据失败')
    # 把session里的数据更新一下

    session['nick=name'] = nick_name

    return jsonify(errno=RET.OK,errmsg='成功')

@profile_blu.route('/pic_info', methods=['GET','POST'])
@user_login_data
def pic_info():
    user = g.user
    if not user:
        return redirect('/')
    if request.method == 'GET':
        data = {
            'user':user.to_dict()
        }
        return render_template('news/user_pic_info.html',data=data)
    # 获取需要上传的文件
    try:
        avatar_file = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.IOERR,errmsg='读取数据失败')

    # 调用工具函数上传图片到七牛云
    try:
        key = storage(avatar_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg='第三方文件上传错误')

    # 把数据保存到用户信息表里
    user.avatar_url = key
    try:
        db.session.commit()
    except Exception as e:
        # 数据错误  需要回滚
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据保存失败')
    # 拼接七牛云的地址
    return jsonify(errno=RET.OK,errmsg='上传照片成功',data={'avatar_url':constants.QINIU_DOMIN_PREFIX + key})


# 修改密码
@profile_blu.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def pass_info():

    # 判断用户是否登陆
    user = g.user
    # 如果没有登录重定向到主页
    if not user:
        return redirect('/')
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')
    # 获取表单数据
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')
    # 判断数据
    if not all([old_password,new_password]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不全')

    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PWDERR,errmsg='原密码错误')
    # 修改数据
    user.password = new_password
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        # 记录错误信息
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='数据库错误')

    return jsonify(errno=RET.OK,errmsg='修改密码成功')


# 用户收藏
@profile_blu.route('/collection')
@user_login_data
def user_collection():
    # 获取参数
    page = request.args.get('p',1)
    # 用强制转换来判断参数是否是int类型
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)#　记录错误日志
        page = 1 #如果参数格式不对 就默认使用1
    # 查询数据库,初始化数据,查询不到就使用默认的
    collections = []
    current_page = 1
    total_page = 1
    user = g.user
    # 查询数据库需要加上try
    try:
        paginate = user.collection_news.paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        # 获取分页数据
        collections = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    # 拼接收藏数据 返回给前端
    collection_dict_li = []

    for temp in collections:
        collection_dict_li.append(temp.to_dict())

    data = {
        'collections':collection_dict_li,
        'total_page':total_page,
        'current_page':current_page
    }
    return render_template('news/user_collection.html',data=data)


@profile_blu.route('/news_release',methods=['GET','POST'])
@user_login_data
def news_release():

    user = g.user
    # 如果用户不存在则跳转到首页
    if not user:
        return redirect('/')
    if request.method == 'GET':

        # 查询分类数据库 获取分类数据
        try:
            categorys = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg='查询数据库失败')

        # 定义一个列表保存数据
        category_dict_li = []
        for temp in categorys:
            category_dict_li.append(temp.to_dict())
        category_dict_li.pop(0)

        data = {
            'categories':category_dict_li
        }
        return render_template('news/user_news_release.html',data=data)

    # 获取表单数据
    title = request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    index_image = request.files.get('index_image')
    content = request.form.get('content')
    # 判断参数是否完整
    if not all([title,category_id,digest,index_image,content]):
        return jsonify(errno=RET.DBERR,errmsg='参数不全')
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='参数不全')
    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.IOERR,errmsg='图片无法打开')
    # 上传图片到七牛云
    try:
        url = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg='第三方错误')
    # 创建新闻实例对象
    news = News()
    news.title = title
    news.source = '个人发布'
    news.content = content
    news.digest = digest
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + url
    news.category_id = category_id
    news.user_id = user.id

    # 设置状态 1 代表审核中
    news.status = 1
    # 保存到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='写入数据库错误')
    # 最后返回成功的结果
    return jsonify(errno=RET.OK,errmsg='发布成功,等待审核')


@profile_blu.route('/news_list')
@user_login_data
def news_list():

    # 获取参数
    page = request.args.get('p', 1)
    # 效验参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    # 查询关联此用户的新闻列表
    user = g.user
    news_model_list = []
    current_page = 1
    total_page = 1
    try:
        paginates = News.query.filter(News.user_id==user.id).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        # 变量名取见名知意的
        news_model_list = paginates.items
        current_page = paginates.page
        total_page = paginates.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询数据库错误')
    # 转数据数据返回给前端
    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_review_dict())
    data = {
        "current_page":current_page,
        "total_page":total_page,
        "news_list":news_dict_li
    }
    return render_template('news/user_news_list.html',data=data)
